package cn.mumzone.pos.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.ItemClickSupport;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.event.AddServiceEvent;
import cn.mumzone.pos.event.RemotePriceChangeEvent;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.ReserveOrderEntity;
import cn.mumzone.pos.model.ServerEntity;
import cn.mumzone.pos.model.ServerResultEntity;
import cn.mumzone.pos.model.ServiceEntity;
import cn.mumzone.pos.presenter.ServiceListPresenter;
import cn.mumzone.pos.presenter.contract.ServiceListContract;
import cn.mumzone.pos.ui.activity.ACT_OpenOrder;
import cn.mumzone.pos.ui.activity.ACT_Schedule;
import cn.mumzone.pos.ui.adapter.ADA_DialogChooseServerList;
import cn.mumzone.pos.ui.adapter.ADA_ServiceList;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;

/**
 * Created by qiuzhenhuan on 2019/6/25.
 */

public class FRA_OpenOrderService extends BaseFragment<ServiceListPresenter> implements ServiceListContract.View {

    private static final String KEY_SELECT_SERVICE = "orderEntity";

    @BindView(R.id.rl_root_service)
    RelativeLayout rlRoot;
    @BindView(R.id.rv_service_list)
    LRecyclerView rvServiceList;
    @BindView(R.id.ll_empty_service)
    LinearLayout llEmptyService;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private LRecyclerView rvServerList;
    private AlertDialog chooseServerDialog;

    ReserveOrderEntity orderEntity;

    private ADA_ServiceList mServiceAdapter;
    private ADA_DialogChooseServerList mServerAdapter;

    private ServiceEntity mSelectService;

    private MemberEntity selectMember;


    private boolean isUpdateMode;

    @Override
    protected void onUserVisible() {
        refreshLayout.autoRefresh();
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        orderEntity = (ReserveOrderEntity) extras.getSerializable(KEY_SELECT_SERVICE);
        isUpdateMode = null != orderEntity;
    }

    @Override
    protected void initEventAndData() {

        initRecyclerView();

        initChooseServerDialog();

        showGoodsList(true);

        refreshLayout.autoRefresh();

        MemberEntity bindMember = null;
        if (orderEntity != null && !StringUtils.isEmpty(orderEntity.getBillingUser())) {
            bindMember = new MemberEntity();
            bindMember.setMemberId(StringUtils.get(orderEntity.getBillingUser()));
            bindMember.setName(StringUtils.get(orderEntity.getBillName()));
            bindMember.setPhone(StringUtils.get(orderEntity.getBillPhone()));
            bindMember.setBirthday(StringUtils.get(orderEntity.getBillBirthday()));
            bindMember.setDiscountType(StringUtils.get(orderEntity.getBillDiscountType()));
        }
        mServiceAdapter.setBindMember(isUpdateMode ? bindMember : selectMember);

        mPresenter.initEvent();

    }

    private void initChooseServerDialog() {
        chooseServerDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_choose_server)
                .setDialogTitle("选择技师")
                .setDialogNoConfirm()
                .setWidthAndHeight(438, 350)
                .create();


        rvServerList = chooseServerDialog.getView(R.id.server_list);
        GridLayoutManager manager = new GridLayoutManager(mContext, 2);
        rvServerList.setLayoutManager(manager);
        mServerAdapter = new ADA_DialogChooseServerList(mContext);
        rvServerList.setAdapter(new LRecyclerViewAdapter(mServerAdapter));
        GridItemDecoration divider = new GridItemDecoration.Builder(mContext)
                .setHorizontal(R.dimen.dp_22)
                .setVertical(R.dimen.dp_20)
                .setColorResource(android.R.color.transparent)
                .build();
        rvServerList.addItemDecoration(divider);

        rvServerList.setHasFixedSize(true);
        rvServerList.setPullRefreshEnabled(false);
        rvServerList.setLoadMoreEnabled(false);

        ItemClickSupport.addTo(rvServerList).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                ServerEntity serverEntity = mServerAdapter.getData().get(position - 1);
                mSelectService.setTechnicianId(serverEntity.getTechnicianId());
                mSelectService.setTechnicianName(serverEntity.getTechnicianName());
                mSelectService.setTechnicianLabel(serverEntity.getTechnicianLabel());
                if (isUpdateMode) {
                    mSelectService.setAppointmentId(orderEntity.getId());
                    mSelectService.setAppointmentTime(orderEntity.getAppointmentTime());
                    mSelectService.setMemberCompanyId(orderEntity.getBillingUser());
                    mPresenter.doAddServiceToReserve(mSelectService);
                } else {
                    closeDialog(chooseServerDialog);
                    RxBus.getDefault().post(new AddServiceEvent(mSelectService.clone()));
                    mSelectService.setSelectCount(mSelectService.getSelectCount() + 1);
                    mServiceAdapter.notifyDataSetChanged();
                }

            }
        });
    }

    private void initRecyclerView() {
        GridLayoutManager serviceManager = new GridLayoutManager(mContext, 3);
        rvServiceList.setLayoutManager(serviceManager);
        mServiceAdapter = new ADA_ServiceList(mContext);
        rvServiceList.setAdapter(new LRecyclerViewAdapter(mServiceAdapter));
        GridItemDecoration serviceDivider = new GridItemDecoration.Builder(mContext)
                .setHorizontal(R.dimen.dp_6)
                .setColorResource(android.R.color.transparent)
                .build();
        rvServiceList.addItemDecoration(serviceDivider);
        rvServiceList.setHasFixedSize(true);
        rvServiceList.setPullRefreshEnabled(false);
        rvServiceList.setLoadMoreEnabled(false);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setOnRefreshListener(new cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                mPresenter.loadServiceList(isUpdateMode ? StringUtils.get(orderEntity.getBillingUser()) :
                        selectMember == null ? "" : StringUtils.get(selectMember.getMemberId()));
            }
        });

        ItemClickSupport.addTo(rvServiceList).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                mSelectService = mServiceAdapter.getData().get(position - 1);
                mPresenter.loadServerList(isUpdateMode ? ServerEntity.UPDATE_TYPE_ADD : ServerEntity.UPDATE_TYPE_NEW
                        , isUpdateMode ? orderEntity.getId() : "",
                        AppDateUtil.getDateToString(isUpdateMode ? Long.parseLong(orderEntity.getAppointmentTime()) : System.currentTimeMillis(), AppDateUtil.YYYY_MM_DD_HH_MM_SS),
                        getAllSelectService(mSelectService));
            }
        });
    }

    private List<ServiceEntity> getAllSelectService(ServiceEntity serviceEntity) {
        ArrayList<ServiceEntity> allSelectService = new ArrayList<>();
        ACT_OpenOrder activity = (ACT_OpenOrder) getActivity();
        if (!isUpdateMode && !ListUtil.isListEmpty(activity.getCartServices())) {
            allSelectService.addAll(activity.getCartServices());
        }
        allSelectService.add(serviceEntity);
        return allSelectService;
    }


    @Override
    public void showServiceList(List<ServiceEntity> list) {
        refreshLayout.finishRefresh();
        ACT_OpenOrder activity = (ACT_OpenOrder) getActivity();
        if (!isUpdateMode && mPresenter.checkLocalAndRemotePrice(list, activity.getCartServices())) {
            RxBus.getDefault().post(new RemotePriceChangeEvent(RemotePriceChangeEvent.TYPE_SERVICE));
        }

        showGoodsList(ListUtil.isListEmpty(list));

        if (orderEntity != null && !ListUtil.isListEmpty(list) && !ListUtil.isListEmpty(orderEntity.getServices())) {
            for (ServiceEntity selectEntity : orderEntity.getServices()) {
                for (ServiceEntity entity : list) {
                    if (selectEntity.getServiceId().equals(entity.getServiceId())) {
                        entity.setSelectCount(entity.getSelectCount() + 1);
                        // TODO: 2019/11/26 结账失败时，收银台金额有可能不对，需要用服务列表的金额数据覆盖收银台列表的金额数据
                        break;
                    }
                }
            }
        }
        if (orderEntity == null && !ListUtil.isListEmpty(mServiceAdapter.getData()) && !ListUtil.isListEmpty(list)) {
            for (ServiceEntity serviceEntity : list) {
                for (ServiceEntity oldEntity : mServiceAdapter.getData()) {
                    if (serviceEntity.getServiceId().equals(oldEntity.getServiceId())) {
                        serviceEntity.setSelectCount(oldEntity.getSelectCount());
                    }
                }
            }
        }
        mServiceAdapter.setData(list);
        mServiceAdapter.notifyDataSetChanged();
    }

    @Override
    public void showServerList(ServerResultEntity serverResult) {

        if (!ListUtil.isListEmpty(serverResult.getList())) {

            chooseServerDialog.toggleShowEmpty(false, R.id.root_view);
            mServerAdapter.setData(serverResult.getList());
            rvServerList.setAdapter(new LRecyclerViewAdapter(mServerAdapter));

            // 根据数据集大小设置弹窗高度
            // 默认高度 300，如果超过 8 条数据，高度就高一点
            if (serverResult.getList().size() > 4) {
                ViewGroup.LayoutParams params = rvServerList.getLayoutParams();
                params.height = Math.min(DisplayUtil.dip2px(mContext, 260), params.height *= 1.3);
                rvServerList.setLayoutParams(params);
            }
        } else {
            if (serverResult.isScheduleOrTechnician()) {
                chooseServerDialog.toggleShowEmpty(true, R.id.root_view, R.drawable.svg_ic_empty_server, "您还没有排班哦~",
                        "立即排班", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (AppConstants.TEMP_USER_PERMISSION != null && AppConstants.TEMP_USER_PERMISSION.isScheduling()) {
                                    ACT_Schedule.startAc(mContext);
                                } else {
                                    PosToast.INSTANCE.makeShortToast(mContext, "无排班权限");
                                }
                            }
                        });
            } else {
                chooseServerDialog.toggleShowEmpty(true, R.id.root_view, R.drawable.svg_ic_empty_server, "您还没有添加技师哦~");
            }
        }

        showDialog(chooseServerDialog);

    }

    @Override
    public void showError(String msg) {
        super.showError(msg);
        refreshLayout.finishRefresh();
    }

    @Override
    public void showRemoveService(ServiceEntity removeServiceEntity) {
        if (!ListUtil.isListEmpty(mServiceAdapter.getData())) {
            for (ServiceEntity entity : mServiceAdapter.getData()) {
                if (removeServiceEntity.getServiceId().equals(entity.getServiceId())) {
                    entity.setSelectCount(entity.getSelectCount() - 1);
                    break;
                }
            }
            mServiceAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showAddServiceToReserveSuccess(String id) {
        mSelectService.setId(id);
        closeDialog(chooseServerDialog);
        RxBus.getDefault().post(new AddServiceEvent(mSelectService.clone()));
        mServiceAdapter.setItemSelectCount(mSelectService.getServiceId(), mSelectService.getSelectCount() + 1);
        mServiceAdapter.notifyDataSetChanged();
    }

    @Override
    public void showAddServiceToReserveError() {
        mSelectService.setId("");
        mSelectService.setTechnicianId("");
        mSelectService.setTechnicianName("");
        mSelectService.setTechnicianLabel("");
        mSelectService.setAppointmentId("");
        mSelectService.setAppointmentTime("");
        mSelectService.setMemberCompanyId("");
    }

    @Override
    public void showMemberChange(MemberEntity memberEntity) {
        selectMember = memberEntity;
        mServiceAdapter.setBindMember(memberEntity);
        mServiceAdapter.notifyDataSetChanged();
    }


    @OnClick({R.id.tv_service_title})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_service_title:
                break;
        }
    }

    public void setOrderEntity(ReserveOrderEntity orderEntity) {
        this.orderEntity = orderEntity;
        isUpdateMode = null != orderEntity;
    }

    private void showGoodsList(boolean isGoodsNull) {
        rvServiceList.setVisibility(isGoodsNull ? View.GONE : View.VISIBLE);
        llEmptyService.setVisibility(isGoodsNull ? View.VISIBLE : View.GONE);
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_open_order_service;
    }


    public static FRA_OpenOrderService getInstance(ReserveOrderEntity orderEntity) {
        FRA_OpenOrderService fragment = new FRA_OpenOrderService();
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_SELECT_SERVICE, orderEntity);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void setMember(MemberEntity memberEntity) {
        selectMember = memberEntity;
    }

}
